﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.Core.DomainModel;
using System.Text.RegularExpressions;

namespace MethodWorx.CMS.Content
{
    public class ChildPageCollection : ChildEntityCollection<Page, Page>
    {
        public ChildPageCollection(Page parent, Func<Page, IEnumerable<Page>> loader)
            : base(parent, loader)
        {

        }

        public Page FindByName(string page)
        {
            this.LoadCollection();
            return this.children.FirstOrDefault(c => c.Name.ToLower() == page.ToLower());
        }

        public MatchedPage Match(string page)
        {
            this.LoadCollection();
            //return this.children.FirstOrDefault(c => c.Name.ToLower() == page.ToLower());
            foreach(var child in this.children)
            {
                if (child.Name.StartsWith("[") && child.Name.EndsWith("]"))
                {
                    var regExpression = new Regex(child.Name.TrimStart('[').TrimEnd(']'));
                    var matches = regExpression.Matches(page);
                    if(matches != null)
                    {
                        //
                        //  ok, go through all the named groups
                        var matchedPage = new MatchedPage(child);
                        foreach(Match m in matches)
                        {
                            for (int counter = 1; counter < m.Groups.Count; counter++)
                            {
                                // If we had just returned the MatchCollection directly, the
                                // GroupNameFromNumber method would not be available to use
                                matchedPage.NamedGroups.Add(regExpression.GroupNameFromNumber(counter), m.Groups[counter].Value);
                            }
                        }
                    }
                }
                else if(child.Name.ToLower() == page.ToLower())
                    return new MatchedPage(child);
            }

            return null;
        }


    }
}
